package com.example.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.example.domain.Drawing;
import com.example.service.DrawingService;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

@Controller
public class DrawingController {

	private final ResourceLoader resourceLoader;
	
	public DrawingController(ResourceLoader resourceLoader) {
		this.resourceLoader = resourceLoader;
	}
	
	@Value("${host.name}")
	private String hostName;
	
	@Autowired
	DrawingService drawingService;
	
	@RequestMapping("/api/drawing/list")
	public String drawingList(Model model){
		List<Drawing> list = drawingService.findAll();
		model.addAttribute("items", list);
		return "drawing/list";
	}
	
	@RequestMapping(value="/api/drawing/save", method=RequestMethod.POST)
	public String saveDrawing(@RequestParam("name") String name,
							@RequestParam("abbreviation") String abbreviation,
							@RequestParam("remark") String remark,
							@RequestParam("type") String type,
							@RequestParam("file") MultipartFile file,
							HttpServletRequest request){
		String contentType = file.getContentType();
		System.out.println("contentType:" + contentType);
		String fileName = file.getOriginalFilename();
		
//		String filePath = request.getSession().getServletContext().getRealPath("upload/");
		long currentTime = System.currentTimeMillis();
		String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
		String targetName = currentTime + suffix;
		try{
			Path filePath = Paths.get("upload", "");
			System.out.println("filePath:" + filePath.toString());
			File targetFile = new File(filePath.toString());
			if(!targetFile.exists()){
				targetFile.mkdirs();
			}
			filePath = Paths.get("upload", targetName);
			System.out.println("Paths:" + Paths.get("upload", targetName));
			// 上传文件，保存到服务器
			FileCopyUtils.copy(file.getBytes(), new FileOutputStream(filePath.toString()));
			//　生成二维码
			// 二维码保存地址
			filePath = Paths.get("upload/qr_code", "");
			System.out.println("filePath:" + filePath.toString());
			targetFile = new File(filePath.toString());
			if(!targetFile.exists()){
				targetFile.mkdirs();
			}
			String qrFilename = currentTime + ".png";
			filePath = Paths.get("upload/qr_code", qrFilename);
			//宽
			int width = 300;
			// 高
			int height = 300;
			// 二维码格式
			String format = "png";
			Map map = new HashMap();
			map.put(EncodeHintType.CHARACTER_SET, "utf-8");
			map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
			map.put(EncodeHintType.MARGIN, 0);
			String url = hostName + "/api/drawing/upload/" + targetName;
			try {
				BitMatrix bm = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, width, height);
				MatrixToImageWriter.writeToPath(bm, format, filePath);
			} catch (WriterException e) {
				e.printStackTrace();
			}catch (IOException e) {
				e.printStackTrace();
			}
			Drawing dw = new Drawing();
			dw.setName(name);
			dw.setAbbreviation(abbreviation);
			dw.setRemark(remark);
			dw.setType(type);
			dw.setPath("/upload/qr_code/" + qrFilename);
			drawingService.insert(dw);
		}catch(Exception e){
			e.printStackTrace();
		}
		return "redirect:/api/drawing/list";
	}
	
	@RequestMapping("/api/drawing/form")
	public String drawingForm(){
		return "drawing/form";
	}
	
	@RequestMapping(value="/api/drawing/upload/qr_code/{filename:.+}", method=RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<Resource> getQrcode(@PathVariable String filename){
		try{
//			Path path = Paths.get("upload", id);
//			System.out.println(path.toUri());
//			Resource resource = new UrlResource(path.toUri());
			HttpHeaders headers = new HttpHeaders();
			MediaType media = new MediaType("image", "jpeg");
			headers.setContentType(media);
			System.out.println(resourceLoader.getResource("file:" + Paths.get("upload/qr_code", filename).toString()));
//			return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get("upload", id).toString()));
			return new ResponseEntity<Resource>(resourceLoader.getResource("file:" + Paths.get("upload/qr_code", filename).toString()),headers, HttpStatus.OK);
		}catch(Exception e){
			System.out.println(e);
			return ResponseEntity.notFound().build();
		}
	}
	
	@RequestMapping(value="/api/drawing/upload/{filename:.+}", method=RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<Resource> getPicture(@PathVariable String filename){
		try{
//			Path path = Paths.get("upload", id);
//			System.out.println(path.toUri());
//			Resource resource = new UrlResource(path.toUri());
			HttpHeaders headers = new HttpHeaders();
			MediaType media = new MediaType("image", "jpeg");
			headers.setContentType(media);
			System.out.println(resourceLoader.getResource("file:" + Paths.get("upload", filename).toString()));
//			return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get("upload", id).toString()));
			return new ResponseEntity<Resource>(resourceLoader.getResource("file:" + Paths.get("upload", filename).toString()),headers, HttpStatus.OK);
		}catch(Exception e){
			System.out.println(e);
			return ResponseEntity.notFound().build();
		}
	}
}
